<?php

class Logger {
    private $logFile;
    private $dateFormat;

    /**
     * Logger constructor.
     * @param string $logFile 日志文件路径
     * @param string $dateFormat 日期格式
     */
    public function __construct($logFile = 'app.log', $dateFormat = 'Y-m-d H:i:s') {
        $this->logFile = $logFile;
        $this->dateFormat = $dateFormat;
    }

    /**
     * 写入日志
     * @param string $message 日志消息
     * @param string $level 日志级别 (info, warning, error等)
     * @return bool
     */
    public function writeLog($message, $level = 'INFO') {
        $timestamp = date($this->dateFormat);
        $logEntry = "[{$timestamp}] [{$level}] {$message}" . PHP_EOL;

        // 确保日志目录存在
        $logDir = dirname($this->logFile);
        if (!is_dir($logDir)) {
            mkdir($logDir, 0755, true);
        }

        // 追加写入日志文件
        return file_put_contents($this->logFile, $logEntry, FILE_APPEND | LOCK_EX) !== false;
    }

    /**
     * 记录信息级别日志
     * @param string $message
     * @return bool
     */
    public function info($message) {
        return $this->writeLog($message, 'INFO');
    }

    /**
     * 记录警告级别日志
     * @param string $message
     * @return bool
     */
    public function warning($message) {
        return $this->writeLog($message, 'WARNING');
    }

    /**
     * 记录错误级别日志
     * @param string $message
     * @return bool
     */
    public function error($message) {
        return $this->writeLog($message, 'ERROR');
    }
}
